import { defineStore } from 'pinia'

interface UserInfo {
  jwt: string
  expiration: number
  user_id: number
  username: string
}

const STORAGE_KEY = 'user_info'

export const useUserStore = defineStore('user', {
  state: () => {
    const storedData = localStorage.getItem(STORAGE_KEY)
    const initialData = storedData
      ? JSON.parse(storedData)
      : {
          jwt: '',
          expiration: 0,
          user_id: 0,
          username: '',
        }

    // 检查数据是否过期
    if (initialData.expiration && initialData.expiration < Date.now()) {
      initialData.jwt = ''
      initialData.expiration = 0
      initialData.user_id = 0
      initialData.username = ''
    }

    return {
      userInfo: initialData as UserInfo,
    }
  },
  actions: {
    setUserInfo(info: UserInfo) {
      this.userInfo = info
      localStorage.setItem(STORAGE_KEY, JSON.stringify(info))
    },
    getUserInfo() {
      return this.userInfo
    },
    clearUserInfo() {
      this.userInfo = {
        jwt: '',
        expiration: 0,
        user_id: 0,
        username: '',
      }
      localStorage.removeItem(STORAGE_KEY)
    },
  },
})
